package org.example.demo2.mq;

import org.example.demo2.config.RabbitmqConfig;
import org.example.demo2.entity.Like;
import org.example.demo2.entity.LikeDTO;
import org.example.demo2.entity.Post;
import org.example.demo2.mapper.LikeMapper;
import org.example.demo2.mapper.PostMapper;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @ClassName Consumer
 * @Description 消费者
 * @Author Kx
 * @Date 2025/10/13 10:06
 * @Version 1.0
 */
// 绑定队列和交换机,并监听队列
@RabbitListener(bindings = @QueueBinding(
        value = @Queue(name = RabbitmqConfig.QUEUE_NAME, durable = "false"),
        exchange = @Exchange(name = RabbitmqConfig.EXCHANGE_NAME, type = ExchangeTypes.DIRECT),
        key = RabbitmqConfig.ROUTING_KEY
))
@Component
public class Consumer {
    @Autowired
    private LikeMapper likeMapper;
    @Autowired
    private PostMapper postMapper;

    @RabbitHandler
    public void receive(LikeDTO likeDTO) {
        if (likeDTO.getLike()) {
            Like like = new Like();
            // 把DTO中的数据复制给实体类
            BeanUtils.copyProperties(likeDTO, like);
            // 添加用户点赞帖子记录
            likeMapper.addLike(like);
        } else {
            // 删除用户点赞帖子记录
            likeMapper.deleteLike(likeDTO.getPostId(), likeDTO.getUserId());
        }

        // 修改帖子点赞量
        Post post = new Post();
        BeanUtils.copyProperties(likeDTO, post);
        postMapper.updatePost(post);
    }
}
